package com.qyl.framework.server.impl;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qyl.framework.base.RPCSwitch;
import com.qyl.framework.handler.InvokeHandler;
import com.qyl.framework.server.decoder.RequestProtoDecoder;
import com.qyl.framework.server.encoder.ResponseProtoEncoder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;

/**
 * 
 * @author created by 齐翌来（qiyilai@foxmail.com）
 * 
 * 2019年2月17日
 * 
 * @description
 *  RPC服务端
 */
public class RPCServer extends RPCSwitch {

	private EventLoopGroup bossGroup, workerGroup;
	
	private static final Logger logger = LoggerFactory.getLogger(RPCServer.class);
	
	@Override
	protected void doStart() {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		
		try {
			ServerBootstrap serverBootstrap = new ServerBootstrap().group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.localAddress(port).childHandler(new ChannelInitializer<SocketChannel>() {
 
						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
		                    ChannelPipeline pipeline = ch.pipeline();  
		                    pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));  
	                        pipeline.addLast(new RequestProtoDecoder());  
	                        pipeline.addLast(new InvokeHandler());
	                        pipeline.addLast(new LengthFieldPrepender(4));
	                        pipeline.addLast(new ResponseProtoEncoder());
						}
					}).childOption(ChannelOption.TCP_NODELAY, true);
			
			this.bossGroup = bossGroup;
			this.workerGroup = workerGroup;
			logger.info("RPCServer started, server listen at port={}", this.port);
			ChannelFuture future = serverBootstrap.bind(port).sync();    
	        future.channel().closeFuture().sync();
		} catch (Exception e) {
			bossGroup.shutdownGracefully();  
	        workerGroup.shutdownGracefully();
	        logger.error("RPCServer started failure", e);
		}
	}
	
	public RPCServer(int port) {
		setPort(port);
	}

	@Override
	protected void doStop() {
		if (bossGroup != null) {
			bossGroup.shutdownGracefully();
		}
		if (workerGroup != null) {
			workerGroup.shutdownGracefully();
		}
		
	}

}
